package com.tedu.charging.service.user.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tedu.charging.service.user.dao.ChargingUserInfoMapper;
import com.tedu.charging.service.user.exception.WXLoginException;

import com.tedu.charging.service.user.pojo.po.ChargingUserInfoPO;
import com.tedu.charging.service.user.pojo.vo.UserVO;
import com.tedu.charging.service.user.service.IChargingUserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;

@Service
@Slf4j
public class ChargingUserInfoServiceImpl implements IChargingUserInfoService {


    @Autowired
    ChargingUserInfoMapper chargingUserInfoMapper;

    @Value("${wx.appId}")
    String appId;
    @Value("${wx.appSecret}")
    String appSecret;


    @Override
    public Integer wxLogin(String code, String nickName) throws Throwable {
        Integer userId = 0;
        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=" + appId +
                "&secret=" + appSecret +
                "&js_code=" + code +
                "&grant_type=authorization_code";
        //利用spring原生http请求工具对接口进行请求
        RestTemplate restTemplate = new RestTemplate();
        String jsonData = restTemplate.getForObject(url, String.class);

        //请求返回的是Json类型的数据 所以我们需要用到fastjson，fastjson是速度比较快的json 解析框架
        JSONObject jsonObject = JSONObject.parseObject(jsonData);
        //这个判断是判断我们的请求是否出错，如果没有出错的话就能够拿到openid
        if (StringUtils.contains(jsonData, "errcode")) {
            //出错了
            log.error("微信登录出错了");
            throw new WXLoginException();
        }
        String openid = jsonObject.getString("openid");

        //生成查询条件，查询open_id存不存在
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("wx_open_id", openid);
        queryWrapper.last("limit 1");

        ChargingUserInfoPO chargingUserInfoPO = chargingUserInfoMapper.selectOne(queryWrapper);

        //判断有没有从数据库中查到数据
        if (chargingUserInfoPO == null) {
            chargingUserInfoPO = new ChargingUserInfoPO();
            chargingUserInfoPO.setWxOpenId(openid);
            chargingUserInfoPO.setNickName(nickName);
            chargingUserInfoMapper.insert(chargingUserInfoPO);
            //查询用户id
            chargingUserInfoPO = chargingUserInfoMapper.selectOne(queryWrapper);
            userId = chargingUserInfoPO.getId();
        } else {
            //已经登录过
            userId = chargingUserInfoPO.getId();
        }

        return userId;
    }

    @Override
    public boolean updateBalance(Integer userId, BigDecimal balance) {

        Integer updateRow = chargingUserInfoMapper.updateBalance(userId, balance);
        return updateRow >= 1 ? true : false;
    }

    @Override
    public boolean recharge(Integer userId, BigDecimal balance) {
        Integer updateRow = chargingUserInfoMapper.recharge(userId, balance);
        return updateRow >= 1 ? true : false;
    }

    @Override
    public UserVO getUser(Integer userId) {
        ChargingUserInfoPO chargingUserInfoPO = chargingUserInfoMapper.selectById(userId);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(chargingUserInfoPO, userVO);
        return userVO;
    }
}
